<template>
    
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 v-model:page="page"
                 v-model:search="search"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @sort-change="sortChange"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @row-dblclick="dbClick"
                 @on-load="onLoad">
        <template #menu-left>
          <el-button
                  type="primary"
                  icon="Message"
                  @click="handleAdd"
          >发 信
          </el-button>
          <el-button type="danger"
                     icon="el-icon-delete"
                     @click="handleDelete">删 除
          </el-button>
        </template>
        <template #menu-right="{disabled}">
          <div style="float: left; padding-right: 20px;">
            <el-radio-group v-model="query.searchType" class="list">

              <el-radio label="1"  @change="refreshChange">近三个月</el-radio>
              <el-radio label="2"  @change="refreshChange">全部</el-radio>
            </el-radio-group>
          </div>
        </template>
        <!--<template #content="{ row }">-->
          <!--<div v-html="row.content" class="div_overhidden"></div>-->
        <!--</template>-->
        <template #hasRead="{ row }">
          <el-tag :type="row.hasRead =='unread' ? 'danger' : 'success'">{{ row.hasRead }}</el-tag>
       </template>
  
        <template #menu="{ row, size, type }">
          <el-tooltip content="查看" placement="top">
            <el-button
                    icon="el-icon-view"
                    link
                    :size="size"
                    :type="type"
                    @click="() => handleView(row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
                    icon="el-icon-delete"
                    link
                    :size="size"
                    :type="type"
                    @click="() => rowDel(row)"
            >
            </el-button>
          </el-tooltip>
        
        </template>
      </avue-crud>
    

      <inbox-info ref="inboxInfoRef" @success="refreshChange"></inbox-info>
  <outbox-info ref="outboxInfoRef" @success="refreshOutBox"></outbox-info>
 
  </template>
  
  <script>
    import {getList, getDetail, add, update, remove, readMsg} from "@/api/anwise/im/im_message";
    import {mapGetters} from "vuex";
    import inboxInfo from "./inbox_info.vue";
    import OutboxInfo from "./outbox_info.vue";
  
    export default {
        components: {
            inboxInfo,
            OutboxInfo
        },
      data() {
        return {
            type:'outbox',
            form: {},
            query: {
                searchType:'1',
            },
            loading: true,
            dateFormat: 'YYYY-MM-DD',
            pickerOptions: {},
            page: {
                pageSize: 20,
                currentPage: 1,
                total: 0
            },
            search:{},
            selectionList: [],
            option: {
                height:'500px',
                calcHeight: 30,
                tip: false,
                searchShow: false,
                searchMenuSpan: 6,
                searchSpan:8,
                border: true,
                index: false,
                selection: true,
                reserveSelection:true,
                labelWidth: 150,
                indexWidth:100,
                menuWidth: 120,
                addBtn: false,
                editBtn: false,
                viewBtn: false,
                delBtn: false,
                stripe: true,
                searchIndex: 3,
                searchIcon: false,
                column: [
                    {
                        label: "发送人",
                        prop: "fromUserName",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                    },
                    {
                        label: "消息类型",
                        prop: "type",
                        type: "select",
                        dicUrl: "/blade-system/dict-biz/dictionary?code=message_type",
                        filterable: true,
                        overHidden: true,
                        search: true,
                        sortable: true,
                        width:120,
                        props: {
                            label: 'dictValue',
                            value: 'dictKey',
                        },
                        dataType: 'string',
                        rules: [{
                            required: false,
                            message: "请输入消息类型",
                            trigger: "blur"
                        }],
                    },
                    {
                        label: "消息内容",
                        prop: "content",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        width:200,
                    },
                    {
                        label: "状态",
                        prop: "hasRead",
                        type: "select",
                        dicUrl: "/blade-system/dict-biz/dictionary?code=message_read_status",
                        filterable: true,
                        overHidden: true,
                        search: true,
                        sortable: true,
                        width:120,
                        props: {
                            label: 'dictValue',
                            value: 'dictKey',
                        },
                        dataType: 'string',
                        rules: [{
                            required: false,
                            message: "请输入状态",
                            trigger: "blur"
                        }],
                    },
                    {
                        label: "发送时间",
                        prop: "createTime",
                        type: "input",
                        width:160,
                        overHidden: true,
                        sortable: true,
                    },
                ]
          },
          data: []
        };
      },
      computed: {
        ...mapGetters(["permission"]),
        permissionList() {
          return {
            addBtn: this.validData(this.permission.customer_group_add, false),
            viewBtn: this.validData(this.permission.customer_group_view, false),
            delBtn: this.validData(this.permission.customer_group_delete, false),
            editBtn: this.validData(this.permission.customer_group_edit, false)
          };
        },
        ids() {
          let ids = [];
          this.selectionList.forEach(ele => {
            ids.push(ele.id);
          });
          return ids.join(",");
        }
      },
      methods: {
          refreshOutBox(){
            this.$emit("success");
          },
          handleAdd() {
              let title="发送站内信";
              let type='edit';
              this.$refs.outboxInfoRef.show({
                  title,
                  type
              })
          },
          dbClick(row){

              readMsg(row.id).then(res=> {
                  this.$store.dispatch("imRead",{fromUserId:row.fromUserId})
              })
              let title="查看详情";
              let type='view';
              const id = row.id;
              this.$refs.inboxInfoRef.show({
                  id,
                  title,
                  type
              })
          },
          handleView(row) {
              readMsg(row.id).then(res=> {
                  this.$store.dispatch("imRead",{fromUserId:row.fromUserId})
              })
              let title="查看详情";
              let type='view';
              const id = row.id;
              this.$refs.inboxInfoRef.show({
                  id,
                  title,
                  type
              })
          },
          sortChange(val) {
              console.log(val)
              this.sort = {
                  prop: val.prop,
                  order: val.order
              };
              let order = "";
              if (this.sort.prop && this.sort.order) {
                  if (this.sort.order === "descending") {
                      order = `${this.sort.prop} desc`
                  } else {
                      order = `${this.sort.prop} asc`
                  }
              }
              this.query.orderBy = order;
              this.onLoad(this.page);
          },
        rowDel(row) {
          this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
                if (row.hasRead=='unread') {
                    this.$store.dispatch("imRead", {fromUserId: row.fromUserId})
                }
              return remove(row.id);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            });
        },
        handleDelete() {
          if (this.selectionList.length === 0) {
            this.$message.warning("请选择至少一条数据");
            return;
          }
          this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
                this.selectionList.forEach(row => {
                    if (row.hasRead=='unread') {
                        this.$store.dispatch("imRead", {fromUserId: row.fromUserId})
                    }
                });
              return remove(this.ids);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.$refs.crud.toggleSelection();
            });
        },
        beforeOpen(done, type) {
          if (["edit", "view"].includes(type)) {
            getDetail(this.form.id).then(res => {
              this.form = res.data.data;
            });
          }
          done();
        },
        searchReset() {
            this.query= {
                searchType: '1',
            };
            this.search.createTimeSearch = '';;
          this.onLoad(this.page);
        },
        searchChange(params, done) {
          this.query = params;
          this.page.currentPage = 1
          this.onLoad(this.page, params);
          done();
        },
        selectionChange(list) {
          this.selectionList = list;
        },
        selectionClear() {
          this.selectionList = [];
          this.$refs.crud.toggleSelection();
        },
        currentChange(currentPage){
          this.page.currentPage = currentPage;
        },
        sizeChange(pageSize){
          this.page.pageSize = pageSize;
        },
        refreshChange() {
          this.onLoad(this.page, this.query);
        },
        onLoad(page, params = {}) {
          this.loading = true;
          params.category = 'inbox';
          getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
            const data = res.data.data;
            this.page.total = data.total;
            this.data = data.records;
            this.loading = false;
            this.selectionClear();
          });
        }
      }
    };
  </script>
  
  <style>
    .div_overhidden{
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      height:50px;
    }
  </style>
  